﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MM.LibraryAPI.ZFB;
using MM.Common;

namespace WebAPI.ZFB
{
    public partial class Notify : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    //获取notify_data数据，需要添加notify_data=
                    //不需要解密，直接是明文xml格式
                    string RequestData = Request.Form["notify_data"] == null ? "" : Request.Form["notify_data"].ToString();
                    string notify_data = "notify_data=" + RequestData;

                    //获取签名
                    string sign = Request.Form["sign"] == null ? "" : Request.Form["sign"].ToString();

                    //LogHelper.WriteLog("验证签名前");

                    //验证签名
                    bool vailSign = Function.Verify(notify_data, sign, Config.Alipaypublick, Config.Input_charset_UTF8);
                    if (!vailSign)
                    {
                        Response.Write("fail");
                        return;
                    }

                    //LogHelper.WriteLog(notify_data);

                    //获取交易状态
                    string trade_status = Function.GetStrForXmlDoc(RequestData, "notify/trade_status");

                    //LogHelper.WriteLog(trade_status);

                    if (!trade_status.Equals("TRADE_FINISHED"))
                    {
                        Response.Write("fail");
                    }
                    else
                    {
                        string OrderID = Function.GetStrForXmlDoc(RequestData, "notify/out_trade_no");

                        if (!string.IsNullOrEmpty(OrderID))
                        {
                            MM.LibraryAPI.Common.SetOrderStatus(OrderID);
                        }

                        //成功必须在页面上输出success，支付宝才不会再发送通知
                        Response.Write("success");

                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("支付宝返回信息异常WebAPI.ZFB：", ex);
            }
        }
    }
}